package ru.spb.osll.myfit.server;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import ru.spb.osll.myfit.common.TextParsingTools;

/**
 * Request filter. Process all fitnesse request
 * 
 */
public class RequestProcessServlet implements Filter {

	static final String[] ENDS_WITH = { ".html", ".css", ".js", ".gif", ".jpg",
			".png", ".ico" };
	static final String[] STARTS_WITH = { "images/" };

	private Logger m_log = Logger.getLogger(this.toString());
	private FilterConfig m_config;

	@Override
	public void destroy() {
	}

	public void init(FilterConfig filterConfig)
			throws javax.servlet.ServletException {
		m_config = filterConfig;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		if ("GET".equals(req.getMethod())) {

			String uri = req.getRequestURI();
			int index = uri.indexOf(TextParsingTools.URI_SEPARATOR);

			m_log.info("request GET");
			m_log.info("uri: " + uri);

			if (index != -1) {
				String path = uri.substring(index + 1);
				if (!isRootAddress(path)) {
					m_log.info("not root address");

					res.setHeader("Pragma", "no-cache");
					res.setHeader("Cache-Control", "must-revalidate");
					res.setHeader("Cache-Control", "no-cache");
					res.setHeader("Cache-Control", "no-store");
					res.setDateHeader("Expires", 0);

					// set path attribute to content.txt
					m_config.getServletContext().setAttribute(
							TextParsingTools.PAGE_PATH_ATTRIBUTE, path);
					m_log.info("set context attribute \"pagePath\" " + path);

					RequestDispatcher dispatch = req.getRequestDispatcher("");
					dispatch.forward(req, res);

					return;
				} else
					m_log.info("root address");
			}
		} else {
			if ("POST".equals(req.getMethod())) {
				m_log.info("request POST");
				m_log.info("uri: " + req.getRequestURI());
			}
		}
		chain.doFilter(req, res);
	}

	/**
	 * Check, the current address is the root address
	 * 
	 * @param path
	 *            - page's path <br>
	 *            (ex. if the address is:
	 *            "http://127.0.0.1:8080/fitnesse/<span style="Font-weight:
	 *            bold">test</span>", then the <code>path</code> is:
	 *            "<span style="Font-weight: bold">test</span>" )
	 * @return result
	 */
	private boolean isRootAddress(String path) {
		m_log.info("path: " + path);
		if (path != null && !path.isEmpty()) {
			for (String str : ENDS_WITH)
				if (path.endsWith(str))
					return true;

			for (String str : STARTS_WITH)
				if (path.startsWith(str))
					return true;

			return false;
		} else {
			m_log.info("type path == null OR path isEmpty");
			return false;
		}
	}
}
